﻿using Fur.DatabaseAccessor;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Linq;

namespace Fur.EntityFramework.Core
{
    [AppDbContext("Data Source=./SaaS.db")]
    public class FurDbContext : AppDbContext<FurDbContext>, IMultiTenantOnTable, IModelBuilderFilter
    {
        public FurDbContext(DbContextOptions<FurDbContext> options) : base(options)
        {
        }

        public object GetTenantId()
        {
            return base.Tenant?.TenantId ?? Guid.Empty;
        }

        public void OnCreating(ModelBuilder modelBuilder, EntityTypeBuilder entityBuilder, DbContext dbContext, Type dbContextLocator)
        {
            entityBuilder.HasQueryFilter(TenantIdQueryFilterExpression(entityBuilder, dbContext));
        }

        protected override void SavingChangesEvent(object sender, SavingChangesEventArgs e)
        {
            var dbContext = sender as FurDbContext;

            // 获取所有新增和更新的实体
            var entities = dbContext.ChangeTracker.Entries().Where(u => u.State == EntityState.Added || u.State == EntityState.Modified);

            foreach (var entity in entities)
            {
                switch (entity.State)
                {
                    // 自动设置租户Id
                    case EntityState.Added:
                        entity.Property(nameof(Entity.TenantId)).CurrentValue = GetTenantId();
                        break;
                    // 排除租户Id
                    case EntityState.Modified:
                        entity.Property(nameof(Entity.TenantId)).IsModified = false;
                        break;
                }
            }
        }
    }
}